const Subscription = require('egg').Subscription;

class UpdateCache extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      interval: '10m', // 10 分钟间隔
      type: 'all', // 指定所有的 worker 都需要执行
      immediate: true,
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    let lastBid = '';
    let sendMsg = this.service.sendMsg;
    let that = this;
    //再次检测是否发布了新视频
    async function detect(lastId) {
      let nowMsg = await that.ctx.curl('http://api.bilibili.com/x/space/arc/search', {
        data: {
          mid: 11563725
        },
        dataType: 'json',
      });
      let now = nowMsg.data.data.list.vlist[0];
      let nowId = now.bvid;
      // console.log(lastId,nowId,lastId != nowId);
      if (lastId != nowId) {
        let videoTitle = now.title;
        let videoPic = 'http:' + now.pic;
        let videoUrl = 'https://www.bilibili.com/video/' + now.bvid;
        await sendMsg.sendToGroup({
          id: 533142992,
          msg: `[CQ:image,file=${videoPic}]\n\n标题：${videoTitle}\n\n视频地址：${videoUrl}`
        });
        console.log(`已发送一条视频推送：${now.bvid}`);
      }else{
        // console.log('nowId:',nowId);
      }
    }
    // 每次刷新最新的视频id
    let res = await this.ctx.curl('http://api.bilibili.com/x/space/arc/search', {
      data: {
        mid: 11563725
      },
      dataType: 'json',
    });
    lastBid = res.data.data.list.vlist[0].bvid;

    setTimeout(function(){
      detect(lastBid);
    },599000)
  }
}

module.exports = UpdateCache;